<?php
namespace app\common\library\payment\type;

use app\common\library\payment\PayMent;

/**
 * 支付宝封装类
 * @author 40215
 *
 */
class Alipay extends PayMent {
    
    // 应用ID
//     private $appId = "2016092800612735";
    private $appId = "2019013163160825";
    
    // 私钥值
    private $rsaPrivateKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDKbIxSyPVWiPvdLGAinsOCSEXop7sW/9gYeeJKIzKFC3geIWyg+5fEkiFod0Amf3PKhxj+XVEoOmEzeaJpCpSrd5S7mENQg8m307xIkHQGEKpeJ8gqb4pbA4zqPwk1WwxOXatLGJ5kfxfC09kNv1K7mYHsmUy85E34iaoAPkGSMcvbzPkDnlq0Zcu6PVUfKWiBv6K93gkW+fFHHwjAFVbCyvhO0KU+/wQR6NhRG8oS8qjOs3W8lrm/HwttHXagPFxgCuAi+v1+5GN4hw9qFmu2JVqYUhZnr7MhT2Q5uGzPv1Vxgiw8PoyIAXW46nQcGbH/hEWG++7xTSRJc2e/4Jo1AgMBAAECggEBAKZBX0NDQJXxboPqxY7JvSRNPfXnhXdPbOo1eVGQ9RZnJCIDK9hQrAdMSlolz6+O8MiAC1wnwtd6k4kWtvj1MsReM++cEHWZuFzeb/9dfZ3ZpEQvAm0wLX+xO9TNLz/+Zu4aau0D7Fv4MsjW/KgY4teoLhjolCl0jkG6t8D5YRuziHOPMK0Dr13XR0QsB3UfV0NvEglzTHv7qKWNoBmJvGPpL6fCurVTOQFe92NfrD5j2eMsD+XPoxN77/zbELmSzZzcowNK1Tsv2cLCoqcJDQNQP0BTCy5AUdAvy5b0kN07Rvv+m93fiYVDPwsZqwkEo/5oFY3vdwcSbSqWn7KG/aECgYEA/YLdFdSX5qXp3OQJtKAOrGGao0BlEbyiEytQqjYUfzbX0eoDq7uiMIa7p40E+i/OCNTIuShn/pwMm0+In1gpsjIYnuD/FjXLGG5kfhJSmypU/5juxp73LApHyKNT3wGAqyp6WE4rGSEOt+AknkYt7ratnWfV4Nyl74UBhkirwukCgYEAzGlKMVyJx0FRVBIAfhAAQao7lPfQTihcqwwktgFnI33nFNSGugVEh/80F7ISu7ZNombUPZNo1w8LZtBYFdfnyeru8zoNQDLNaWiKD4QGgyGhdXY/d9x9MRqvJcwgBWooyWAhOu2KmH1+HmpNZO9aSqw22yc5ZdI2+TLcUXHFlW0CgYEAkHZcSi5liVgOloOUTEvRUMYl+tWdQqg9q7LJOtWqhHvaLJKwGNLJr+F3WhlwNqm7PSkUYP73lA2U2YRPFI6G5DbL9O2+Lwfkfj2aIoWKcUWEPksF9kVsELqjAWChULloeyGvqlaRFLbTzlB6TX8seZW8BbDAHm1eWclvfvg2eNECgYEAgkp2dQIj+/KhUTHsSG4Qi8pjEe/nQXounwQtfilkwVWl7jwM6BMlfH3piVUC5c0srOBYVitYfwPi45TXII0u/CAYUMZm3c3D6nUs0vj3YawVCxblG5RZ4+u7Sh9TJcBl4P26EKKKXepXcjGVxUlfRwuAJ65XwpP8YFjP38XiB/0CgYA06FOJWdJaNMjJ0XTLUwW5f7e98rppTBwdZrz46ua66+94a0kbhRetqRHUQX3oDRUfI01dmw9sv5oNRUyRSsgbPgSelPMQkObpohq8zsV8YPKEXpEbIi0ycLHLBIGb1YeBQ0u+ArCrFLT2nHiKj8BHqTmZ+6pP57F7566JVJBTiA==";
    
    // 私钥文件路径
    private $rsaPrivateKeyFilePath = "";
    
    // 网关
    private $gatewayUrl = "https://openapi.alipay.com/gateway.do";
    
    // 返回数据格式
    private $format = "json";
    
    // api版本
    private $version = "1.0";
    
    // 表单提交字符集编码
    private $postCharset = "UTF-8";
    
    // 支付宝公钥
    private $alipayPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6RmyFwOgnh3W34hD54cngLbyEJ5ftgGVTV9CIMLKi5fIk6uWLJim/VATfQG9/NPHHHGXZnNSRULNoH/WtDW10GMyvdTOIrvKjxARMhwwTD+0MR6Tfc/OcDjKmI1sUpFS12CMih7UgOnnf4Utz9X7itmeIP7JV8l1HeWLn3sQ47h60zAvMrUfkfhonP94x/UdUmeHUBVjthxlOSsB4WrQR+lpr7hbjnEO5HJfmi2127YDNpMB8mjAM7r8QCe3Jitovb5E1X0qcORMwb0lVlPmtst5Y8rIiW1TQ9ZHosZ6FuKeTmKUx8d/ZlMQUzDV1F0Gy12/yy/YEFHdFJb0QHGoDQIDAQAB';
    
    // 签名类型
    private $signType = "RSA2";
    
    
    public function unifiedorder($title, $out_trade_no, $total)
    {
        $content = [];
        $content['product_code'] = 'QUICK_MSECURITY_PAY';
//         $content['product_code'] = 'FAST_INSTANT_TRADE_PAY';
        $content['total_amount'] = $total;
        $content['out_trade_no'] = $out_trade_no;
        $content['subject'] = $content['body'] = $title;
        $biz_content = json_encode($content, JSON_UNESCAPED_UNICODE);
        
        $params = [];
        $params['app_id'] = $this->appId;
        $params['method'] = 'alipay.trade.app.pay';
//         $params['method'] = 'alipay.trade.page.pay';
        $params['charset'] = $this->postCharset;
        $params['sign_type'] = $this->signType;
        $params['timestamp'] = date('Y-m-d H:i:s');
        $params['version'] = $this->version;
        $params['notify_url'] = url('api/pay/ali_notify', null, false, true);
        $params['biz_content'] = $biz_content;
        ksort($params);
        $params['sign'] = $this->generateSign($params);
        
//         $result = $this->buildRequestForm($params);
//         echo $result;
        
        return http_build_query($params);
    }
    
    public function check($data)
    {
        return $this->rsaCheckV1($data, null);
    }
    
    /**
     * 建立请求，以表单HTML形式构造（默认）
     * @param array $para_temp 请求参数数组
     * @return string 提交表单HTML文本
     */
    protected function buildRequestForm($para_temp) {
        $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='".$this->gatewayUrl."?charset=".trim($this->postCharset)."' method='POST'>";
        foreach ($para_temp as $key => $val){
            if (false === $this->checkEmpty($val)) {
                //$val = $this->characet($val, $this->postCharset);
                $val = str_replace("'","&apos;",$val);
                //$val = str_replace("\"","&quot;",$val);
                $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
            }
        }
        
        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml."<input type='submit' value='ok' style='display:none;''></form>";
        
        $sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
        
        return $sHtml;
    }
    
    protected function sign($data, $signType = "RSA2") {
        if($this->checkEmpty($this->rsaPrivateKeyFilePath)){
            $priKey = $this->rsaPrivateKey;
            $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
                wordwrap($priKey, 64, "\n", true) .
                "\n-----END RSA PRIVATE KEY-----";
        }else {
            $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
            $res = openssl_get_privatekey($priKey);
        }
        
        ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');
        
        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
        } else {
            openssl_sign($data, $sign, $res);
        }
        
        if(!$this->checkEmpty($this->rsaPrivateKeyFilePath)){
            openssl_free_key($res);
        }
        
        $sign = base64_encode($sign);
        return $sign;
    }
    
    /**
     * 生成签名
     * @param array $params
     * @param string $signType
     * @return string
     */
    protected function generateSign($params, $signType = "RSA2"){
        return $this->sign($this->getSignContent($params), $signType);
    }
    
    /**
     * 此方法对value做urlencode 
     * @param array $params
     * @return string
     */
    protected function getSignContentUrlencode($params) {
        ksort($params);
        
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                
                // 转换成目标字符集
                $v = $this->characet($v, $this->postCharset);
                
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . urlencode($v);
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . urlencode($v);
                }
                $i++;
            }
        }
        
        unset ($k, $v);
        return $stringToBeSigned;
    }
    
    /**
     * 获取签名排序字符串
     * @param array $params
     * @return string
     */
    protected function getSignContent($params) {
        ksort($params);
        
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                
                // 转换成目标字符集
                $v = $this->characet($v, $this->postCharset);
                
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        
        unset ($k, $v);
        return $stringToBeSigned;
    }
    
    /**
     * 转换字符集编码
     * @param string $data 数据源 
     * @param string $targetCharset 目标字符集
     * @return string
     */
    private function characet($data, $targetCharset) {
        
        if (!empty($data)) {
            $fileType = $this->postCharset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
            }
        }
        
        return $data;
    }
    
    /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     */
    protected function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
                    
        return false;
    }
    
    /** 
     * 验证签名 rsaCheckV1
     * @param array $params
     * @param string $rsaPublicKeyFilePath 公钥路径
     * @param string $signType 验签类型
     * @return boolean
     * 在使用本方法前，必须初始化AopClient且传入公钥参数。
     * 公钥是否是读取字符串还是读取文件，是根据初始化传入的值判断的。
     */
    protected function rsaCheckV1($params, $rsaPublicKeyFilePath, $signType='RSA2') {
        $sign = $params['sign'];
        $params['sign_type'] = null;
        $params['sign'] = null;
        return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
    }
    /**
     * 验证签名 rsaCheckV2
     * @param array $params
     * @param string $rsaPublicKeyFilePath 公钥路径
     * @param string $signType 验签类型
     * @return boolean
     */
    protected function rsaCheckV2($params, $rsaPublicKeyFilePath, $signType='RSA2') {
        $sign = $params['sign'];
        $params['sign'] = null;
        return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
    }
    
        
    private function verify($data, $sign, $rsaPublicKeyFilePath, $signType = 'RSA2') {
        if (! $this->checkEmpty($this->alipayPublicKey)) {
            $pubKey = $this->alipayPublicKey;
            $res = "-----BEGIN PUBLIC KEY-----\n" .
                wordwrap($pubKey, 64, "\n", true) .
                "\n-----END PUBLIC KEY-----";
        } else {
            // 读取公钥文件
            $pubKey = file_get_contents($rsaPublicKeyFilePath);
            // 转换为openssl格式密钥
            $res = openssl_get_publickey($pubKey);
        }
        
        ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
        
        // 调用openssl内置方法验签，返回bool值
        
        $result = FALSE;
        if ("RSA2" == $signType) {
            $result = (openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256)===1);
        } else {
            $result = (openssl_verify($data, base64_decode($sign), $res)===1);
        }
        
        if ($this->checkEmpty($this->alipayPublicKey)) {
            // 释放资源
            openssl_free_key($res);
        }
        
        return $result;
    }
    

    
}